﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FrameWorkCore.NewtonsoftJson
{
    /// <summary>
    /// Filter the null
    /// </summary>
    internal class NullToEmptyStringResolver : CamelCasePropertyNamesContractResolver
    {
      
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            return type.GetProperties().Select(c =>
            {
                var jsonProperty = base.CreateProperty(c, memberSerialization);
                    jsonProperty.PropertyName = jsonProperty.PropertyName.ToLower();
                    jsonProperty.ValueProvider = new NullToEmptyStringValueProvider(c);
                return jsonProperty;
            }).ToList();
        }
    }

    public class NullToEmptyStringValueProvider : IValueProvider
    {
        private readonly PropertyInfo _memberInfo;

        public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
        {
            _memberInfo = memberInfo;
        }


        public object GetValue(object target)
        {
            var result = _memberInfo.GetValue(target);
            if (_memberInfo.PropertyType == typeof(string) && result == null)
                result = string.Empty;
            return result;
        }

        public void SetValue(object target, object value)
            => _memberInfo.SetValue(target, value);

    }

}
